import * as types from './mutation-types'
import * as addrAPI from '@/api/addr.js'
import {fetchApplyCount} from "@/api/group.js"
import * as cache from '@/utils/storage.js'
import DC from "@/DC/index.js"
import { User } from '@/entity/User'
import { Group } from "@/entity/Group"
// #ifdef APP-PLUS
import { pathByUrl,downToPath } from "@/services/mediaService"
// #endif

export default {
	async init({dispatch,rootState:{user:{userInfo}}}){
		if(!userInfo){
			throw new Error('请登录')
		}
		dispatch('fetchAllFriends')
		dispatch('fetchAllgroups')
	},
	async fetchAllFriends({commit,dispatch}){
		let friends = []
		let pageNo = 0
		let pageSize = 999
		do{
			pageNo++
		    const list = await addrAPI.fetchFriends({pageNo,pageSize})
			  friends.push(...list.map((item)=>{
				const user = User.creatNullIns({...item})
				user.sex = item.sex
				user.remarks = item.remarks
				user.profiles = item.profiles
				user.userNum = item.userNum
				user.buddy = true
				// #ifdef APP-PLUS
				pathByUrl(user.avatarUrl).then((path)=>{
					if(path){
						user.saveAvatar = path
					}else{
						downToPath(user.avatarUrl).then((newPath)=>{
							user.saveAvatar = newPath
						})
					}
				})
				// #endif
				DC.userDB.setUser(user)
				return user
			}))
		}while(friends.length>=pageNo*pageSize)
		commit(types.SET_FRIENDS,friends)
		return friends
	},
	async saveFriends({state:{friends},rootState:{user:{userInfo}}}){
		await cache.set(`addr_friends_${userInfo.userId}`,friends)
	},
	async loadOneFriend({state:{friends},commit,dispatch},uid){
		const friend = await addrAPI.fetchFriendByUid(uid)
		const user = User.creatNullIns({...friend})
		user.sex = friend.sex
		user.remarks = friend.remarks
		user.profiles = friend.profiles
		user.userNum = friend.userNum
		user.buddy = true
		if(friends.some((item)=>{
			if(item.userId==user.userId){
				item.mixIns(user)
				return true
			}
		})){
		}else{
			commit(types.SET_FRIENDS,[user,...friends])
		}
		dispatch('saveFriends')
		return user
	},
	async pushFriend({state:{friends},commit,dispatch},friend){
		commit(types.SET_FRIENDS,[...friends,friend])
		await dispatch('saveFriends')
	},
	async removeFriend({state:{friends},commit,dispatch},id){
		commit(types.SET_FRIENDS,friends.filter(({userId})=>id!=userId))
		await dispatch('saveFriends')
	},
	async updateFriend({state:{friends},commit,dispatch},{userId,...info}){
		commit(types.SET_FRIENDS,friends.map((item)=>{
			return item.userId==userId?{...item,...info}:item
		}))
		dispatch('saveFriends')
	},
	async fetchAllgroups({commit,dispatch}){
		let groups = []
		let pageNo = 0
		let pageSize = 999
		do{
			pageNo++
		    const list = await addrAPI.fetchGroups({pageNo,pageSize})
			groups.push(...list.map((item)=>{
				const group = Group.origin2Ins(item)
				// #ifdef APP-PLUS
				pathByUrl(group.avatar).then((path)=>{
					if(path){
						group.saveAvatar = path
					}else{
						downToPath(group.avatar).then((newPath)=>{
							group.saveAvatar = newPath
						})
					}
				})
				// #endif
				DC.groupDB.setGroup(group)
				return group
			}))
		}while(groups.length>=pageNo*pageSize)
		commit(types.SET_GROUPS,groups)
		return groups
	},
	async saveGroups({state:{groups},rootState:{user:{userInfo}}}){
		await cache.set(`addr_groups_{userInfo.userId}`,groups)
	},
	async removeGroup({state:{groups},commit,dispatch},id){
		commit(types.SET_GROUPS,groups.filter(item=>item.id!=id))
	},
	async clear({commit}){
		commit(types.SET_FRIENDS,[])
		commit(types.SET_GROUPS,[])
	},
	async fetchPendApplyCount({commit}){
		const count = await addrAPI.fetchApplyCount(addrAPI.APPLY_STATE.pending)
		commit(types.SET_APPR_COUNT,count)
	},
	async fetchApplies({commit,rootGetters}){
		const list = await addrAPI.fetchApplyList({pageNo:1,pageSize:20,status:0})
		const userId = rootGetters['user/userId']
		const count = list.reduce((r,n)=>{
			if(n.toUserId == userId){
				return r+1
			}
			return r
		},0)
		commit(types.SET_APPR_COUNT,count)
		if(count){
			uni.showTabBarRedDot({index:1})
		}else{
			uni.hideTabBarRedDot({index:1})
		}
	},
	async fetchGroupJoin({commit}){
		const num = await fetchApplyCount({status:0})
		commit(types.SET_GROUP_JOIN_COUNT,num||0)
	},
}
